import {
  Controller,
  Get,
  Post,
  Put,
  Delete,
  Param,
  Body,
  NotFoundException,
} from '@nestjs/common';
import { UsersService } from './users.service';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { User } from './entities/user.entity';
// 导入认证相关装饰器和守卫
import { UseGuards } from '@nestjs/common';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';

// @UseGuards(JwtAuthGuard) - 如果添加在这里，所有接口都需要认证
@Controller('users')
export class UsersController {
  constructor(private readonly usersService: UsersService) {}

  // GET /users - 获取所有用户
  @Get()
  @UseGuards(JwtAuthGuard) // 只保护这个接口
  async findAll(): Promise<User[]> {
    return this.usersService.findAll();
  }

  // GET /users/:id - 获取单个用户
  @Get(':id')
  async findOne(@Param('id') id: string): Promise<User> {
    try {
      // 将字符串类型的id转换为数字并调用服务的findOne方法
      return await this.usersService.findOne(Number(id));
    } catch (error) {
      // 捕获可能的异常并返回友好的错误信息
      throw new NotFoundException(error.message`用户 ID ${id} 不存在`);
    }
  }

  // POST /users - 创建用户
  @Post()
  async create(@Body() createUserDto: CreateUserDto): Promise<User> {
    // @Body() 装饰器从请求体中提取数据并自动转换为CreateUserDto类型
    return await this.usersService.create(createUserDto);
  }

  // PUT /users/:id - 更新用户信息
  @Put(':id')
  async update(
    @Param('id') id: string,
    @Body() updateUserDto: UpdateUserDto,
  ): Promise<User> {
    try {
      // 调用服务的update方法更新用户信息
      return await this.usersService.update(+id, updateUserDto);
    } catch (error) {
      throw new NotFoundException(error.message`用户 ID ${id} 不存在`);
    }
  }

  // DELETE /users/:id - 删除用户
  @Delete(':id')
  async remove(@Param('id') id: string): Promise<{ message: string }> {
    try {
      await this.usersService.remove(Number(id));
      // 返回成功消息
      return { message: '用户已成功删除' };
    } catch (error) {
      throw new NotFoundException(error.message`用户 ID ${id} 不存在`);
    }
  }
}
